﻿using System;
using System.IO;
using System.Collections.Generic;

namespace DreamCube.Foundation.DllImport
{
    /// <summary>
    /// 文件路径：C:\WINDOWS\system32\shdocvw.dll
    /// Windows应用程序添加基础文件和网络操作相关模块。
    /// </summary>
    public static class Myshdocvw
    {
        #region "内部枚举值"

        /// <summary>
        /// url匹配的规则
        /// </summary>
        public enum UrlMatchType
        {
            /// <summary>
            /// 完整匹配
            /// </summary>
            FullMatch,

            /// <summary>
            /// 前缀匹配
            /// </summary>
            StartWith
        }

        #endregion

        #region "公共方法"

        /// <summary>
        /// 判断本机浏览器是否打开了某个网页（只兼容IE浏览器）
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
#if NET20
        public static Boolean IsBrowserOpenUrl(String url, UrlMatchType matchType = UrlMatchType.FullMatch)
#else
        public static Boolean IsBrowserOpenUrl(this String url, UrlMatchType matchType = UrlMatchType.FullMatch)
#endif
        {
            SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
            String filename = null;
            foreach (SHDocVw.InternetExplorer ie in shellWindows)
            {
                filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
                if (filename.Equals("iexplore"))
                {
                    if (matchType == UrlMatchType.FullMatch && String.Compare(ie.LocationURL, url, true) == 0)
                        return true;
                    else if (matchType == UrlMatchType.StartWith && ie.LocationURL.StartsWith(url, StringComparison.CurrentCultureIgnoreCase))
                        return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获取本机浏览器打开的网站（只兼容IE浏览器）
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static String[] GetBrowserOpenUrls()
        {
            SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
            String filename = null;
            List<String> urls = new List<String>();
            foreach (SHDocVw.InternetExplorer ie in shellWindows)
            {
                filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
                if (filename.Equals("iexplore"))
                    urls.Add(ie.LocationURL);
            }
            return urls.ToArray();
        }

        #endregion
    }
}
